<?php

namespace App\Repository;

use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Sales\AfterSalesApply;
use App\Models\Sales\AfterSalesApplyItem;
use Illuminate\Support\Facades\Log;

/**
 * 订单售后仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class AfterSalesRepository extends BaseRepository
{
    /**
     * 保存数据
     *
     * @param array $data
     * @param int $applyId
     * @throws
     * @return int|mixed
     */
    public function save(array $data, int $applyId = 0)
    {
        try {
            $query = $applyId ? AfterSalesApply::find($applyId) : new AfterSalesApply();
            collect($data)->each(function ($value, $field) use ($query) {
                $query->{$field} = $value;
            });
            if(!$query->save()) {
                throw new \Exception('售后申请主单保存失败');
            }
            return $query->apply_id;
        } catch (\Exception $exception) {
            Log::error("[售后申请单] 保存失败：{$exception->getMessage()}");
            throw new BusinessException(ResponseCode::SAVE_FAIL);
        }
    }

    /**
     * 保存明细数据
     *
     * @param array $data
     * @throws
     * @return bool
     */
    public function saveItem(array $data)
    {
        try {
            collect($data)->each(function ($item) {
                $query = empty($item->item_id) ? new AfterSalesApplyItem() : AfterSalesApplyItem::find($item->item_id);
                collect($item)->each(function ($value, $field) use ($query) {
                    $query->{$field} = $value;
                });
                if(!$query->save()) {
                    throw new \Exception('售后申请明细单保存失败');
                }
            });
            return true;
        } catch (\Exception $exception) {
            Log::error("[售后申请单] 保存失败：{$exception->getMessage()}");
            throw new BusinessException(ResponseCode::SAVE_FAIL);
        }
    }

    /**
     * 获取列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getList(array $filter = [])
    {
        $query = AfterSalesApply::query()->orderByDesc('created_at')->with(['items' => function($query) {
            return $query->select('*');
        }]);
        if(!empty($filter['state'])) {
            $query->where('state', $filter['state']);
        }
        if(!empty($filter['order_bn'])) {
            $query->where('order_bn', $filter['order_bn']);
        }
        if(!empty($filter['nickname'])) {
            $query->where('customer_name', 'like', '%' . $filter['nickname'] . '%');
        }
        if(!empty($filter['start_at'])) {
            $query->where('created_at', '>=', $filter['start_at']);
        }
        if(!empty($filter['end_at'])) {
            $query->where('end_at', '<=', $filter['end_at']);
        }
        if(!empty($filter['apply_bn'])) {
            $query->where('apply_bn', $filter['apply_bn']);
        }
        if(!empty($filter['customer_id'])) {
            $query->where('customer_id', $filter['customer_id']);
        }
        return $query;
    }

    /**
     * 根据售后申请单 Id 获取记录
     *
     * @param int $applyId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getApplyById(int $applyId)
    {
        return AfterSalesApply::query()->where('apply_id', $applyId)->with(['items' => function($query) {
            return $query->select('*');
        }])->first();
    }
}
